<script setup lang="ts">
import {ref, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {
  ElDialog,
  ElTabs,
  ElTabPane,
  ElForm,
  ElFormItem,
  ElInput,
  ElSwitch,
  ElSelect,
  ElButton,
  ElMessageBox
} from 'element-plus'
import {Delete, Check, Plus} from '@element-plus/icons-vue'
import axios from 'axios'
import ajax from "../main.ts";

interface Server {
  id: number
  name: string
  isPublic: string
  enabled: string
  description: string
  type: string
  command: string
  args: string
  env: string
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible'])

const activeTab = ref('personal')
const activeServer = ref<number | 'new'>(0)

const servers = ref<Server[]>([])

const isNewServer = ref(false)

const form = ref<Server>({
  id: 0,
  name: '',
  isPublic: "0",
  enabled: "1",
  description: '',
  type: 'stdio',
  command: '',
  args: '',
  env: ''
})

// 获取服务器列表
const fetchServers = async () => {
  try {
    const response = await ajax.get('getServer/')
    if (response.data.code === 200) {
      servers.value = response.data.data
      if (servers.value.length > 0) {
        handleServerClick(servers.value[0])
      }
    } else {
      ElMessage.error(response.data.msg)
    }
  } catch (error) {
    console.error('获取服务器列表失败:', error)
  }
}

// 监听弹窗显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    fetchServers()
  } else {
    // 弹窗关闭时重置状态
    isNewServer.value = false
    if (servers.value.length > 0) {
      activeServer.value = servers.value[0].id
      handleServerClick(servers.value[0])
    }
  }
})

const handleServerClick = (server: Server | 'new') => {
  if (server === 'new') {
    activeServer.value = 'new'
    form.value = {
      id: 0,
      name: '',
      isPublic: "0",
      enabled: "1",
      description: '',
      type: 'stdio',
      command: '',
      args: '',
      env: ''
    }
  } else {
    activeServer.value = server.id
    form.value = {...server}
  }
}

const handleAddServer = () => {
  isNewServer.value = true
  handleServerClick('new')
}

const handleDelete = async () => {
  if (isNewServer.value) {
    try {
      await ElMessageBox.confirm(
          '确定要取消新建服务器吗？',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            customClass: 'delete-confirm-dialog',
            confirmButtonClass: 'confirm-btn',
            cancelButtonClass: 'cancel-btn',
            distinguishCancelAndClose: true
          }
      )
      isNewServer.value = false
      activeServer.value = 1
      handleServerClick(servers.value[0])
    } catch {
      // 用户点击取消，不做任何操作
    }
  } else {
    try {
      await ElMessageBox.confirm(
          '确定要删除该服务器吗？',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            customClass: 'delete-confirm-dialog',
            confirmButtonClass: 'confirm-btn',
            cancelButtonClass: 'cancel-btn',
            distinguishCancelAndClose: true
          }
      )
      // 调用删除接口
      await ajax.post(`delServer/`, {id: form.value.id})
      // 从列表中移除该服务器
      const index = servers.value.findIndex(server => server.id === activeServer.value)
      if (index !== -1) {
        servers.value.splice(index, 1)
        // 如果删除的是当前选中的服务器，则选择第一个服务器
        if (servers.value.length > 0) {
          activeServer.value = servers.value[0].id
          handleServerClick(servers.value[0])
        } else {
          // 如果没有服务器了，则显示新建服务器
          isNewServer.value = true
          handleServerClick('new')
        }
      }
      fetchServers();
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除服务器失败:', error)
      }
    }
  }
}

const handleSave = async () => {
  try {
    const response = await ajax.post('saveServer/', form.value)
    if (response.data.code === 200) {
      ElMessage.success(response.data.msg)
      fetchServers();
      if (isNewServer.value) {
        isNewServer.value = false
        // 保存后自动选择第一个服务器
        activeServer.value = 1
        handleServerClick(servers.value[0])
      }
    } else {
      ElMessage.error(response.data.msg)
    }
  } catch (error) {
    console.error('更新服务器失败:', error)
  }
}

</script>

<template>
  <el-dialog
      :model-value="props.visible"
      title="MCP设置"
      width="800px"
      :close-on-click-modal="false"
      @update:model-value="(val) => emit('update:visible', val)"
      class="settings-dialog"
  >
    <el-tabs v-model="activeTab">
      <el-tab-pane label="我的" name="personal">
        <div class="settings-content">
          <div class="server-list">
            <div class="add-server-btn" @click="handleAddServer">
              <el-icon>
                <Plus/>
              </el-icon>
              <span>添加服务器</span>
            </div>
            <div
                v-if="isNewServer"
                class="server-item new-server"
                :class="{ active: activeServer === 'new' }"
                @click="handleServerClick('new')"
            >
              新建服务器
            </div>
            <div
                v-for="server in servers"
                :key="server.id"
                class="server-item"
                :class="{ active: activeServer === server.id }"
                @click="handleServerClick(server)"
            >
              {{ server.name }}
            </div>
          </div>
          <div class="server-config">
            <el-form :model="form" label-width="100px">
              <el-form-item label="MCP名称" required>
                <el-input v-model="form.name" maxlength="30" placeholder="自定义MCP名称"/>
              </el-form-item>
              <el-form-item label="是否开放">
                <el-switch v-model="form.isPublic" active-value="1" inactive-value="0"/>
              </el-form-item>
              <el-form-item label="是否启用">
                <el-switch v-model="form.enabled" active-value="1" inactive-value="0"/>
              </el-form-item>
              <el-form-item label="MCP描述">
                <el-input v-model="form.description" type="textarea" maxlength="300"
                          placeholder="MCP server的简单描述"/>
              </el-form-item>
              <el-form-item label="MCP类型" required>
                <el-select v-model="form.type">
                  <el-option label="标准输入输出(stdio)" value="stdio"/>
                  <el-option label="服务器发送事件(sse)" value="sse"/>
                </el-select>
              </el-form-item>
              <el-form-item label="MCP命令" required>
                <el-input v-model="form.command" placeholder="uvx或者npx"/>
              </el-form-item>
              <el-form-item label="MCP参数">
                <el-input v-model="form.args" type="textarea" maxlength="500"
                          placeholder="每个参数占一行"/>
              </el-form-item>
              <el-form-item label="环境变量">
                <el-input v-model="form.env" type="textarea" maxlength="500" placeholder="每个key=value占一行"/>
              </el-form-item>
              <el-form-item>
                <div class="form-actions">
                  <el-button class="delete-btn" @click="handleDelete">
                    <el-icon>
                      <Delete/>
                    </el-icon>
                    <span>删除</span>
                  </el-button>
                  <el-button class="save-btn" type="primary" @click="handleSave">
                    <el-icon>
                      <Check/>
                    </el-icon>
                    <span>保存</span>
                  </el-button>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="公共" name="public">
        <div class="public-content">
          <!-- 公共配置内容 -->
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<style scoped>
.settings-content {
  display: flex;
  height: 500px;
}

.server-list {
  width: 200px;
  border-right: 1px solid #dcdfe6;
  padding-right: 20px;
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: rgba(99, 102, 241, 0.3) rgba(99, 102, 241, 0.1);
}

.server-list::-webkit-scrollbar {
  width: 20px;
}

.server-list::-webkit-scrollbar-track {
  background: rgba(99, 102, 241, 0.1);
  border-radius: 10px;
}

.server-list::-webkit-scrollbar-thumb {
  background: rgba(99, 102, 241, 0.3);
  border-radius: 10px;
  border: 6px solid transparent;
  background-clip: content-box;
}

.server-list::-webkit-scrollbar-thumb:hover {
  background: rgba(99, 102, 241, 0.4);
  background-clip: content-box;
}

.server-item {
  padding: 10px;
  cursor: pointer;
  border-radius: 4px;
  margin-bottom: 5px;
}

.server-item:hover {
  background-color: #f5f7fa;
}

.server-item.active {
  background-color: #ecf5ff;
  color: #409eff;
}

.server-item.new-server {
  color: #6366f1;
  font-weight: 500;
  border: 1px dashed #6366f1;
  background: rgba(99, 102, 241, 0.05);
}

.server-item.new-server.active {
  background: rgba(99, 102, 241, 0.1);
  border-color: #4f46e5;
}

.server-config {
  flex: 1;
  padding-left: 20px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.server-config :deep(.el-form) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.server-config :deep(.el-form-item) {
  margin-bottom: 16px;
}

.server-config :deep(.el-form-item:last-child) {
  margin-top: auto;
  margin-bottom: 0;
}

.public-content {
  height: 500px;
  overflow-y: auto;
}

:deep(.el-dialog) {
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(16px);
  -webkit-backdrop-filter: blur(16px);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(0, 0, 0, 0.05);
}

:deep(.el-dialog__header) {
  padding: 20px;
  margin: 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

:deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
  background: linear-gradient(135deg, #6366f1, #8b5cf6);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

:deep(.el-dialog__body) {
  padding: 20px;
  max-height: 70vh;
}

:deep(.el-tabs__item) {
  font-size: 14px;
  font-weight: 500;
}

:deep(.el-tabs__item.is-active) {
  color: #6366f1;
}

:deep(.el-tabs__active-bar) {
  background-color: #6366f1;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: auto;
  padding: 16px 0;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
}

.delete-btn {
  padding: 8px 16px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  background: transparent;
  color: #ef4444;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  display: flex;
  align-items: center;
  gap: 6px;
}

.delete-btn:hover {
  background: rgba(239, 68, 68, 0.1);
  border-color: #ef4444;
}

.delete-btn:active {
  background: rgba(239, 68, 68, 0.2);
}

.save-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 8px;
  background: linear-gradient(135deg, #6366f1, #8b5cf6);
  color: white;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  display: flex;
  align-items: center;
  gap: 6px;
  box-shadow: 0 2px 6px rgba(99, 102, 241, 0.2);
}

.save-btn:hover {
  background: linear-gradient(135deg, #4f46e5, #7c3aed);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
}

.save-btn:active {
  transform: translateY(0);
  background: linear-gradient(135deg, #4338ca, #6d28d9);
  box-shadow: 0 2px 6px rgba(99, 102, 241, 0.2);
}

.add-server-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px;
  margin-bottom: 12px;
  cursor: pointer;
  color: #6366f1;
  font-size: 14px;
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.3s ease;
  border: 1px dashed #6366f1;
}

.add-server-btn:hover {
  background: rgba(99, 102, 241, 0.1);
  color: #4f46e5;
  border-color: #4f46e5;
}

.add-server-btn .el-icon {
  font-size: 16px;
}

:deep(.delete-confirm-dialog) {
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(16px);
  -webkit-backdrop-filter: blur(16px);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(0, 0, 0, 0.05);
  width: 400px;
}

:deep(.delete-confirm-dialog .el-message-box__header) {
  padding: 24px 24px 16px;
  margin: 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

:deep(.delete-confirm-dialog .el-message-box__title) {
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.delete-confirm-dialog .el-message-box__title::before) {
  content: '';
  display: inline-block;
  width: 4px;
  height: 16px;
  background: linear-gradient(135deg, #6366f1, #8b5cf6);
  border-radius: 2px;
}

:deep(.delete-confirm-dialog .el-message-box__content) {
  padding: 24px;
  color: #4b5563;
  font-size: 14px;
  line-height: 1.6;
}

:deep(.delete-confirm-dialog .el-message-box__btns) {
  padding: 16px 24px;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.delete-confirm-dialog .confirm-btn) {
  padding: 8px 16px;
  border: none;
  border-radius: 8px;
  background: linear-gradient(135deg, #6366f1, #8b5cf6);
  color: white;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  box-shadow: 0 2px 6px rgba(99, 102, 241, 0.2);
}

:deep(.delete-confirm-dialog .confirm-btn:hover) {
  background: linear-gradient(135deg, #4f46e5, #7c3aed);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
}

:deep(.delete-confirm-dialog .confirm-btn:active) {
  transform: translateY(0);
  background: linear-gradient(135deg, #4338ca, #6d28d9);
  box-shadow: 0 2px 6px rgba(99, 102, 241, 0.2);
}

:deep(.delete-confirm-dialog .cancel-btn) {
  padding: 8px 16px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  background: transparent;
  color: #4b5563;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
}

:deep(.delete-confirm-dialog .cancel-btn:hover) {
  background: rgba(0, 0, 0, 0.05);
  color: #1a1a1a;
  border-color: rgba(0, 0, 0, 0.2);
}

:deep(.delete-confirm-dialog .el-message-box__status) {
  display: none;
}

:deep(.delete-confirm-dialog .el-message-box__message) {
  padding-left: 0;
}

:deep(.el-message-box) {
  background: rgba(255, 255, 255, 0.98) !important;
  backdrop-filter: blur(16px) !important;
  -webkit-backdrop-filter: blur(16px) !important;
  border-radius: 16px !important;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1) !important;
  border: 1px solid rgba(0, 0, 0, 0.05) !important;
  width: 400px !important;
}

:deep(.el-message-box__header) {
  padding: 24px 24px 16px !important;
  margin: 0 !important;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05) !important;
}

:deep(.el-message-box__title) {
  font-size: 18px !important;
  font-weight: 600 !important;
  color: #1a1a1a !important;
  display: flex !important;
  align-items: center !important;
  gap: 8px !important;
}

:deep(.el-message-box__title::before) {
  content: '' !important;
  display: inline-block !important;
  width: 4px !important;
  height: 16px !important;
  background: linear-gradient(135deg, #6366f1, #8b5cf6) !important;
  border-radius: 2px !important;
}

:deep(.el-message-box__content) {
  padding: 24px !important;
  color: #4b5563 !important;
  font-size: 14px !important;
  line-height: 1.6 !important;
}

:deep(.el-message-box__btns) {
  padding: 16px 24px !important;
  border-top: 1px solid rgba(0, 0, 0, 0.05) !important;
  display: flex !important;
  justify-content: flex-end !important;
  gap: 12px !important;
}

:deep(.el-message-box__btns .el-button--primary) {
  padding: 8px 16px !important;
  border: none !important;
  border-radius: 8px !important;
  background: linear-gradient(135deg, #6366f1, #8b5cf6) !important;
  color: white !important;
  font-size: 14px !important;
  font-weight: 500 !important;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1) !important;
  box-shadow: 0 2px 6px rgba(99, 102, 241, 0.2) !important;
}

:deep(.el-message-box__btns .el-button--primary:hover) {
  background: linear-gradient(135deg, #4f46e5, #7c3aed) !important;
  transform: translateY(-1px) !important;
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3) !important;
}

:deep(.el-message-box__btns .el-button--primary:active) {
  transform: translateY(0) !important;
  background: linear-gradient(135deg, #4338ca, #6d28d9) !important;
  box-shadow: 0 2px 6px rgba(99, 102, 241, 0.2) !important;
}

:deep(.el-message-box__btns .el-button--default) {
  padding: 8px 16px !important;
  border: 1px solid rgba(0, 0, 0, 0.1) !important;
  border-radius: 8px !important;
  background: transparent !important;
  color: #4b5563 !important;
  font-size: 14px !important;
  font-weight: 500 !important;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1) !important;
}

:deep(.el-message-box__btns .el-button--default:hover) {
  background: rgba(0, 0, 0, 0.05) !important;
  color: #1a1a1a !important;
  border-color: rgba(0, 0, 0, 0.2) !important;
}

:deep(.el-message-box__status) {
  display: none !important;
}

:deep(.el-message-box__message) {
  padding-left: 0 !important;
}
</style> 